package com.example.leavemanagement.controller;


import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.leavemanagement.annotation.AuthCheck;
import com.example.leavemanagement.common.BaseResponse;
import com.example.leavemanagement.common.ResultUtils;
import com.example.leavemanagement.constant.UserConstant;
import com.example.leavemanagement.exception.ErrorCode;
import com.example.leavemanagement.exception.ThrowUtils;
import com.example.leavemanagement.model.dto.leave.LeaveAddRequest;
import com.example.leavemanagement.model.dto.leave.LeaveQueryRequest;
import com.example.leavemanagement.model.dto.leave.LeaveReviewRequest;
import com.example.leavemanagement.model.dto.leave.LeaveTagCategory;
import com.example.leavemanagement.model.entity.LeaveInfo;
import com.example.leavemanagement.model.entity.User;
import com.example.leavemanagement.model.vo.LeaveVo;
import com.example.leavemanagement.service.LeaveInfoService;
import com.example.leavemanagement.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 黄宽亮
 * @version 1.0
 * @description: TODO
 * @date 2025/4/30 08:44
 */
@RestController
@RequestMapping("/leave")
@Slf4j
public class leaveController {

    @Resource
    LeaveInfoService leaveInfoService;

    @Resource
    UserService userService;

    /**
     * 用户
     * @param leaveAddRequest
     * @param request
     * @return
     */
    @PostMapping("/addLeave")
    @AuthCheck
    public  BaseResponse<Boolean> addLeave(@RequestBody LeaveAddRequest leaveAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(leaveAddRequest==null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(leaveInfoService.addLeaveInfo(leaveAddRequest, request));
    }
    /**
     * 管理员
     * 分页获取请假列表
     * @param leaveQueryRequest
     * @return
     */
    @PostMapping("/getLeavePage")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<LeaveVo>> getLeavePage(@RequestBody LeaveQueryRequest leaveQueryRequest) {
        ThrowUtils.throwIf(leaveQueryRequest==null, ErrorCode.NOT_FOUND_ERROR);
        int pageSize = leaveQueryRequest.getPageSize();
        int current = leaveQueryRequest.getCurrent();
        Page<LeaveInfo> leavePage = leaveInfoService.page(new Page<>(current, pageSize), leaveInfoService.getQueryWrapper(leaveQueryRequest));
        List<LeaveInfo> records = leavePage.getRecords();
        //将leaveInfo对象转换成leaveVo对象
        List<LeaveVo>  listLeaveVo = records.stream().map(LeaveVo::objToVo).collect(Collectors.toList());
        //用set集合接收审核人的id，防止id重复
        Set<Long> userIdSet=records.stream().map(LeaveInfo::getReviewerId).collect(Collectors.toSet());
        //通过id获取用户信息
        Map<Long, List<User>> userMap = userService.listByIds(userIdSet).stream().collect(Collectors.groupingBy(User::getId));
        if(ObjUtil.isNotEmpty(userMap)){
            //将每个User放入新的Page对象中
            listLeaveVo.forEach(leaveVo ->{
                Long userId = leaveVo.getUserId();
                User user=null;
                if(userMap.containsKey(userId)){
                    user = userMap.get(userId).get(0);
                }
                //将获得的user转换成userVo
                leaveVo.setUser(userService.getUserVo(user));
            });
        }
        Page<LeaveVo> leaveVoPage = new Page<>();
        leaveVoPage.setRecords(listLeaveVo);
        return ResultUtils.success(leaveVoPage);
    }

    /**
     * 获取请假分类
     * @return
     */
    @GetMapping("/tag_category")
    @AuthCheck
    public BaseResponse<LeaveTagCategory> listPictureTagCategory() {
        LeaveTagCategory leaveTagCategory = new LeaveTagCategory();
        List<String> categoryList = Arrays.asList("病假", "事假", "招聘面试", "丧假", "其他");
        leaveTagCategory.setCategoryList(categoryList);
        return ResultUtils.success(leaveTagCategory);
    }

    /**
     * 审核请假情况
     * @param leaveReviewRequest
     * @param request
     * @return
     */
    @PostMapping("/review")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> doLeaveReview(@RequestBody LeaveReviewRequest leaveReviewRequest,HttpServletRequest request){
        ThrowUtils.throwIf(ObjUtil.isNull(leaveReviewRequest)||ObjUtil.isNull(request),ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        leaveInfoService.doLeaveReview(leaveReviewRequest,loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 查询当前用户的请假信息
     * @param request
     * @return
     */
    @GetMapping("/getUserLeaveInfo")
    @AuthCheck
    public BaseResponse<List<LeaveVo>> getLeaveInfo(HttpServletRequest request){
        ThrowUtils.throwIf(request==null,ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        return ResultUtils.success(leaveInfoService.getUserLeaveInfoList(loginUser));
    }
}
